﻿using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using Random = UnityEngine.Random;

namespace UFrame
{
    /// <summary>
    /// UI测试
    /// </summary>
    public sealed class AutoTestUI : Singleton<AutoTestUI>
    {
        private AutoTestUI()
        {
        }

        public Dictionary<int, GameObject> uiRootDic = new Dictionary<int, GameObject>();
        public GameObject currentUI;
        public float operationTime = 0;
        private float operationTimer = 0;
        public Type uiType;
        public UITestGroupJson uiTestTemplate;


        public void FindUI()
        {
            var uiList = GameObject.FindObjectsOfType(uiType);
            bool test = true;
            currentUI = null;
            int ordering = 0;

            foreach (var ui in uiList)
            {
                if (ui == null)
                {
                    Debug.LogError("退出测试");
                    test = false;
                    break;
                }

                bool isActive = false;
                if (ui is MonoBehaviour)
                {
                    var mono = ui as MonoBehaviour;
                    isActive = mono.gameObject.activeSelf;
                    Canvas c = mono.GetComponent<Canvas>();

                    if (isActive && ordering < c.sortingOrder)
                    {
                        ordering = c.sortingOrder;
                        currentUI = mono.gameObject;
                    }
                }
                else if (ui is GameObject)
                {
                    var go = ui as GameObject;
                    isActive = go.activeSelf;
                    Canvas c = go.GetComponent<Canvas>();

                    if (isActive && ordering < c.sortingOrder)
                    {
                        ordering = c.sortingOrder;
                        currentUI = go;
                    }
                }
                else
                {
                    Debug.LogError("不支持的类型: " + ui.GetType().Name);
                }
            }
        }


        public void RunTemplateTest()
        {
            AutoTestUIEntity entity = GetUIControl();


            //绑定控件
            foreach (var inputJson in uiTestTemplate.inputList)
            {
                Vector3 pos = inputJson.position;
                foreach (var control in entity.controlList)
                {
                    RectTransform rt = control.transform as RectTransform;
                    if (RectTransformUtility.RectangleContainsScreenPoint(rt, pos, Camera.main))
                    {
                        Debug.Log("存在这个控件内: " + control.name);
                        inputJson.control = control;
                        break;
                    }
                }
            }

            //绑定一组控件
            foreach (var item in uiTestTemplate.groupList)
            {
                //item.ids
            }
        }

        public AutoTestUIEntity GetUIControl()
        {
            AutoTestUIEntity entity = new AutoTestUIEntity();
            if (currentUI == null || currentUI.ToString() == "null")
            {
                currentUI = null;
                return null;
            }

            var eventList = currentUI.GetComponentsInChildren<EventTrigger>();
            var btnList = currentUI.GetComponentsInChildren<Button>();
            var toggleList = currentUI.GetComponentsInChildren<Toggle>();
            var inputList = currentUI.GetComponentsInChildren<InputField>();
            var textList = currentUI.GetComponentsInChildren<Text>();

            entity.eventTriggerAry = eventList;
            entity.buttonAry = btnList;
            entity.toggleAry = toggleList;
            entity.inputFieldAry = inputList;
            entity.textAry = textList;

            entity.controlList.AddRange(btnList);
            entity.controlList.AddRange(toggleList);
            entity.controlList.AddRange(inputList);
            entity.controlList.AddRange(textList);
            entity.controlList.AddRange(eventList);

            return entity;
        }

        public void TestCurrentUI()
        {
            AutoTestUIEntity entity = GetUIControl();


            var index = Random.Range(0, entity.controlList.Count);

            if (entity.controlList.Count == 0)
            {
                return;
            }
            else if (index >= entity.controlList.Count)
            {
                Debug.LogError("执行操作超出长度: " + entity.controlList.Count);
                return;
            }

            var element = entity.controlList[index];
            if (element is Button)
            {
                ((Button)element).onClick.Invoke();
            }

            if (element is EventTrigger)
            {
                //((EventTrigger)element).OnPointerUp(new PointerEventData());
            }
            else if (element is Toggle)
            {
                bool isOn = Random.Range(0, 1) > 0;
                ((Toggle)element).onValueChanged.Invoke(isOn);
            }
            else if (element is InputField)
            {
                InputField f = ((InputField)element);
                ((InputField)element).text = "aasdadas";
                //((InputField)element).onValueChanged.Invoke();
            }
            else if (element is Text)
            {
                ((Text)element).text = "测试测试测试测试测试测试测试测试测试测试";
            }
            else
            {
                Debug.Log("界面: " + currentUI.name + " 无法执行: " + element.gameObject.name);
            }

            Debug.Log("界面: " + currentUI.name + " 执行: " + element.gameObject.name);
            operationTimer = Time.time + operationTimer;
        }


        public AutoTestGroup ConvertJson(AutoTestGroupJson uiGroup)
        {
            /*List<AutoTestInput> inputList = new List<AutoTestInput>();
            foreach (var group in uiGroup.inputList)
            {
                GameObject autoInput = CreateNode();
                var input = autoInput.AddComponent<AutoTestInput>();
                autoInput.name = strAutoInput + group.id;
                input.id = group.id;
                inputList.Add(input);
            }
    
            //创建新的UI测试
            foreach (var group in uiGroup.groupList)
            {
                GameObject autoInput = CreateNode();
                var input = autoInput.AddComponent<AutoTestGroup>();
                autoInput.name = strAutoInputGroup + group.id;
                input.id = group.id;
    
                input.randomTestList = new List<AutoTestInput>();
                foreach (var id in group.ids)
                {
                    foreach (var item in inputList)
                    {
                        if (id == item.id)
                        {
                            input.randomTestList.Add(item);
                            break;
                        }
                    }
                }
    
                //顺序测试
    
                foreach (var order in group.orderToTestList)
                {
                    string orderStr = string.Empty;
    
                    foreach (var item in order.ids)
                    {
                        orderStr += item + ",";
                    }
    
                    orderStr = orderStr.TrimEnd(',');
                    input.orderToTest.Add(orderStr);
                }
            }*/
            return null;
        }
    }


    /// <summary>
    /// 存储UI的全部按钮和toggle 
    /// </summary>
    public class AutoTestUIEntity
    {
        public EventTrigger[] eventTriggerAry;
        public Button[] buttonAry;
        public Toggle[] toggleAry;
        public InputField[] inputFieldAry;
        public Text[] textAry;
        public List<MonoBehaviour> controlList;
    }
}